package com.haocjia.esdemo.elastic.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.haocjia.esdemo.elastic.service.ElasticSearchService;
import com.haocjia.esdemo.elastic.utils.MappingUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Configuration;

import java.util.Map;

@Slf4j
@Configuration
@RequiredArgsConstructor
public class EsApplicationRunner implements ApplicationRunner {

    @Value("#{'${es.indexs}'.split(',')}")
    private String[] index;
    @Value("#{'${es.entity}'.split(',')}")
    private String[] entity;


    private final ElasticSearchService elasticSearchService;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        if (index != null) {
            ObjectMapper mapper = new ObjectMapper();

            for (int i = 0; i < index.length; i++) {
                Boolean exists = elasticSearchService.exists(index[i]);
                if (exists) {
                    continue;
                }
                Class<?> aClass = Class.forName(entity[i]);
                Map<String, Object> mapping = MappingUtils.getMapping(aClass.newInstance());
                log.info("索引创建:{}", mapper.writeValueAsString(mapping));
                elasticSearchService.createIndex(index[i], mapper.writeValueAsString(mapping), 1, 0);
            }
        }
    }

}
